<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type = "text/javascript">
	async function postData(url = "", data = {}){
	  const response = await fetch(url, {
	    method: "POST",
	    headers:{
		  "Accept" : "application/json",
	      "Content-Type": "application/json",
	    },
	    body: JSON.stringify(data),
	  });
	  return response.json();
	}

	function ListBooks(books) {
		  var booklist = document.getElementById("bookList");
		  booklist.innerHTML = "";

		  for (let book of books) {
		    var div = document.createElement("div");

		    var bookName = document.createElement("div");
		    bookName.innerHTML = book.name;

		    var price = document.createElement("div");
		    price.innerHTML = "价格: " + book.price; // 改为中文 "价格"

		    var amount = document.createElement("div");
		    amount.innerHTML = "库存: " + book.amount; // 改为中文 "库存"

		    var buyButton = document.createElement("button");
		    buyButton.textContent = "购买"; // 改为中文 "购买"

			buyButton.onclick = function(){
		    	purchase(book)
		    }

		    div.appendChild(bookName);
		    div.appendChild(price);
		    div.appendChild(amount);
		    div.appendChild(buyButton);

		    booklist.appendChild(div);
		  }
		}


	function purchase(b){
		console.log("Buy this book : ")
		console.log(b)
		postData("./store/purchase",{
			book : b
		})
		.then((resp) =>{
			console.log(resp.status)
			if (resp.status == "OK"){
				loadPage()
			}else{
				alert(resp.status)
			}
		})
	}

	function loadAccount(acc){
		if (acc >= 0){
			document.getElementById("account")
				.innerHTML = "账户余额 : " + acc 
		}
	}
	
	function loadPage(){
		postData("./store/getBooks",{})
	      .then((data) => {
	    	console.log(data.status)
	        ListBooks(data);
    	})
    	postData("./store/getAccount",{})
    		.then((data) =>{
    			loadAccount(data.balance)
    		})
	}
	
</script>
</head>




<body onload ="loadPage()">
	<div align = "center">
		<div>你好,${visitorType}</div>
		<div id = "account"></div>
		<div>
		<button id = "log" onclick = "location.href = ${actionUrl}">${actionName}</button>
		</div>
	</div>
	
	<hr>
	<hr>
	<br>
	<br>
	
	<div id = "bookList" align = "center">
		<div >
			<div>《老人与海》</div>
			<div>price : 10</div>
			<div>amount : 5</div>
			<button onclick = "alert('购买')">购买</button>
			<br>
			<br>
		</div>
		
		<div >
			<div>《老人与海》</div>
			<div>price : 10</div>
			<div>amount : 5</div>
			<button onclick = "alert('购买')">购买</button>
			<br>
			<br>
		</div>
	</div>
	
</body>
</html>